package com.example.administrator.officeplatform.Activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;

import com.example.administrator.officeplatform.MyApplication;
import com.example.administrator.officeplatform.R;
import com.example.administrator.officeplatform.base.BaseActivity;
import com.example.administrator.officeplatform.base.CheckPermission;
import com.example.administrator.officeplatform.bean.Constant;
import com.example.administrator.officeplatform.utils.JsonUtil;
import com.google.gson.reflect.TypeToken;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity {
    private AutoCompleteTextView actv_userName;
    private Button btn_register, btn_login;
    private EditText et_userName, et_pwd;
    private ProgressDialog mProgressDialog;
    private Context mContext;
    private Toolbar toolbar;
    private Boolean isrunning = false;
    private Boolean autologin = false;
    private String UserType;
    private String msession;
    private String orgId="",userid="",realName="",departName="";

    private static final int CANCELLED = 3;
    private long exitTime=0;
    private static final int REQUEST_CODE = 0;//请求码

    private CheckPermission checkPermission;//检测权限器

    //配置需要取的权限
    static final String[] PERMISSION = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
            Manifest.permission.READ_EXTERNAL_STORAGE,  //读取权限
            Manifest.permission.CAMERA,//相机权限
            Manifest.permission.READ_PHONE_STATE,//手机状态
            Manifest.permission.ACCESS_COARSE_LOCATION,//位置信息
            Manifest.permission.ACCESS_FINE_LOCATION, //
    };
    private OkHttpClient mOkHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        btn_login = (Button) findViewById(R.id.btn_login);
//        btn_register = (Button) findViewById(R.id.btn_register);
        et_userName = (EditText) findViewById(R.id.et_userName);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("登录");
        toolbar.setNavigationIcon(null);
        setSupportActionBar(toolbar);
//        actv_userName.setText(MyApplication.getUserInfo().getUsername());
//        et_password.setText(MyApplication.getUserInfo().getPassword());
        readUserContent();
        checkPermission = new CheckPermission(this);

    }

    @Override
    protected void initEvents() {
        btn_login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent();
//                intent.setClass(mContext, HomeActivity.class);
//                startActivity(intent);
                Login();
            }
        });
    }


    class myOnClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {

                default:
                    break;
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        //缺少权限时，进入权限设置页面
        if (checkPermission.permissionSet(PERMISSION)) {
            startPermissionActivity();
        }
    }

    //进入权限设置页面
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, REQUEST_CODE, PERMISSION);
    }

    //返回结果回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拒绝时，没有获取到主要权限，无法运行，关闭页面
        if (requestCode == REQUEST_CODE && resultCode == PermissionActivity.PERMISSION_DENIEG) {
            finish();
        }
    }

    private void Login() {

        if (et_userName.getText().toString().trim().length() == 0) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_LONG).show();
            return;
        }
        if (et_pwd.getText().toString().trim().length() == 0) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_LONG).show();
            return;
        }
        String userName = et_userName.getText().toString();
        String password = et_pwd.getText().toString();
        postAsynHttp(userName, password);
    }

    /**
     * post异步请求
     * {"userAccount":"superbx","userPassword":123456,"appCode":"reimbursement"}
     */

    public void postAsynHttp(String username,String password) {
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("userAccount", username)
                .add("userPassword", password)
                .add("appCode", "reimbursement")
//                .add("origin", "192.168.5.14")
//                .add("port", "8871")
                .build();
        Request request = new Request.Builder()
//                .url("http://192.168.5.244:8866/sso/login")
                .url("http://103.239.152.13:8866/sso/login")
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接服务器异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Log.i("wangshu", str);
                mProgressDialog.dismiss();
                int i = str.indexOf("orgId");
                if(str.indexOf("orgId")<=0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "登录异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }else {
                    if(str.indexOf("orgId")>=0){
                        String userMsg = JsonUtil.getMsg(str, "user");
                        String orgIdMsg = JsonUtil.getMsg(userMsg,"orgId");
                        userid = JsonUtil.getMsg(userMsg,"id");
                        realName = JsonUtil.getMsg(userMsg,"name");
                        departName = JsonUtil.getMsg(userMsg,"orgName");

                        List<String> ls_id = JsonUtil.getPersons(orgIdMsg, new TypeToken<List<String>>() {
                        }.getType());
                        orgId=ls_id.get(0);
                    }
                    //获取session的操作，session放在cookie头，且取出后含有“；”，取出后为下面的 s （也就是jsesseionid）
                    Headers headers = response.headers();
                    Log.d("info_headers", "header " + headers);
                    List<String> cookies = headers.values("Set-Cookie");
                    String session = cookies.get(0);
                    Log.d("info_cookies", "onResponse-size: " + cookies);

                    msession = session.substring(0, session.indexOf(";"));

                    Log.i("info_s", "session is  :" + msession);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.setClass(mContext, HomeActivity.class);
                            startActivity(intent);
                            saveUserContent();
                            finish();
                        }
                    });

                }


            }

        });
    }


    private void saveUserContent() {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        MyApplication.setIsUserLogin(true);
        MyApplication.setMsession(msession);
        MyApplication.setUsername(et_userName.getText().toString().trim());
        MyApplication.setPasword(et_pwd.getText().toString().trim());
        MyApplication.setOrgId(orgId);

        edit.putString("userName", et_userName.getText().toString().trim());
        edit.putString("pwd", et_pwd.getText().toString().trim());
        edit.putString("session",msession);
        edit.putString("orgId",orgId);
        edit.putString("userid",userid);
        edit.putString("realName",realName);
        edit.putString("departName",departName);
        edit.commit();
    }

    private void readUserContent() {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                Context.MODE_PRIVATE);
        et_userName.setText(sharedPreferences.getString("userName", ""));
        et_pwd.setText(sharedPreferences.getString("pwd", ""));
    }




    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序。", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}



